package com.shadt.cloud.filter;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * session拦截器
 * 
 * @author SongR
 *
 */
@Repository
public class SessionInterceptor extends HandlerInterceptorAdapter {
	public void postHandle(
			HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception {
	}

	public void afterCompletion(
			HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		String[] noFilters = new String[] { "login","register" };
		String uri = request.getRequestURI();
		if (uri.indexOf("admin") != -1) {
			boolean beFilter = true;
			for (String s : noFilters) {
				if (uri.indexOf(s) != -1) {
					beFilter = false;
					break;
				}
			}
			if (beFilter) {
				Object obj = request.getSession().getAttribute("userinfo");
				if (null == obj) {
					String s = request.getHeader("x-requested-with"); 
					if(null!=s){
						PrintWriter p = response.getWriter();
						p.println("timeout");
						
					}else{
						response.sendRedirect("../admin/loginpage");
					}
					
					return false;
				} else {
					
				}
			}
		}
		return super.preHandle(request, response, handler);
	}
}
